package com.bnd.domain.session;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.audio.asr.recognition.Recognition;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionParam;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionResult;
import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.ResultCallback;
import jakarta.websocket.Session;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@EqualsAndHashCode(callSuper = true)
@Slf4j
@Data
public class WsChatSessionV2 extends BaseChatSession{
    private AtomicBoolean allowAiSpeech = new AtomicBoolean(false);
    private Object ttsLock = new Object();
    private Object asrLock = new Object();
    private AtomicBoolean asrSessionReady = new AtomicBoolean(false);


    public boolean allowAiSpeech() {
        return allowAiSpeech.get();
    }

    public boolean asrSessionReady() {
        return asrSessionReady.get();
    }

    public void setAsrSessionReady(boolean asrSessionReady) {
        this.asrSessionReady.set(asrSessionReady);
    }

    public void setAllowAiSpeech(boolean allowAiSpeech) {
        this.allowAiSpeech.set(allowAiSpeech);
    }



    /**
     * 语音合成缓冲区
     */
    private ByteBuffer ttsByteBuffer;

    /**
     * 语音识别缓冲区
     */
    private ByteBuffer asrByteBuffer;

    /**
     * 语音识别客户端
     */
    private Recognition recognition;

    /**
     * 语音合成客户端
     */
    private SpeechSynthesizer speechSynthesizer;

    /**
     * 语音识别参数
     */
    private RecognitionParam recognitionParam;

    /**
     * 语音合成参数
     */
    private SpeechSynthesisParam speechSynthesisParam;

    /**
     * 语音合成回调
     */
    private ResultCallback<SpeechSynthesisResult> ttsCallback;

    /**
     * 语音识别
     */
    private ResultCallback<RecognitionResult> asrCallback;

    /**
     * 对话客户端
     */
    private Generation generation;

    private List<Message> newMessageList;


    public WsChatSessionV2(String chatId, Long characterId, Session session) {
        this.chatId = chatId;
        this.characterId = characterId;
        this.session = session;
        this.messageList = CollectionUtil.newArrayList();
        // 写模式：position=0, limit=capacity
        this.ttsByteBuffer = ByteBuffer.allocate(8 * 1024);
        this.asrByteBuffer = ByteBuffer.allocate(8 * 1024);
        this.recognition = new Recognition();
        this.generation = new Generation();
        this.newMessageList = CollectionUtil.newArrayList();
    }
}
